<!--
 * @Author: your name
 * @Date: 2021-12-30 16:26:42
 * @LastEditTime: 2022-01-26 18:02:30
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \jingfeng_version2\src\views\feedBack\turnBug\aa.vue
-->
<!--
 * @Author: your name
 * @Date: 2021-08-10 10:16:21
 * @LastEditTime: 2021-12-30 16:24:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jinfeng_up\src\views\feedBack\turnBug\turnBug.vue
-->
<template>
    <div class="turnBug">
        <el-page-header class="header" @back="toBefore" content="">
            <template slot="title"> 转BUG </template>
            <template slot="content">
                <el-button class="option_btn" @click="SaveBug">发布</el-button>
            </template>
        </el-page-header>
        <div class="createWrap">
            <div class="createContainer">
                <el-form
                    class="turnBugForm"
                    :model="turnBugForm"
                    ref="dynamicValidateForm"
                    :rules="turnBugFormRules"
                    label-position="left"
                    label-width="80px"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-row>
                                <el-col :span="15">
                                    <el-form-item
                                        label="所属产品"
                                        prop="product"
                                    >
                                        <el-select
                                            v-model="turnBugForm.product"
                                            class="acordProduct"
                                            filterable
                                            clearable
                                            @change="productChange"
                                        >
                                            <el-option
                                                v-for="(
                                                    item, index
                                                ) in allProductList"
                                                :key="index"
                                                :label="item.name"
                                                :value="item.productId"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="9" class="productBranch">
                                    <el-form-item
                                        prop="branch"
                                        label="产品分支"
                                    >
                                        <el-select
                                            v-model="turnBugForm.branch"
                                            placeholder="请选择产品分支"
                                            class="acordBranch"
                                            filterable
                                            clearable
                                        >
                                            <el-option
                                                :value="0"
                                                label="全部分支"
                                            ></el-option>
                                            <el-option
                                                v-for="(
                                                    item, index
                                                ) in ProductBranchList"
                                                :key="index"
                                                :label="item.name"
                                                :value="item.id"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="所属模块"
                                class="Marketing"
                                prop="module"
                            >
                                <el-select
                                    v-model="turnBugForm.module"
                                    placeholder="请选择所属模块"
                                    class="userSelect"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(item, index) in ModuleList"
                                        :key="index"
                                        :label="item.name"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="所属项目" prop="project">
                                <el-select
                                    v-model="turnBugForm.project"
                                    placeholder="请选择所属项目"
                                    class="userSelect"
                                    @change="projectChange"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(item, index) in ProjectList"
                                        :key="index"
                                        :label="item.name"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- TODO 影响版本下拉接口 -->
                        <el-col :span="12">
                            <el-form-item label="影响版本" prop="openedbuild">
                                <el-select
                                    v-model="turnBugForm.openedbuild"
                                    class="userSelect"
                                    placeholder="请选择影响版本"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(
                                            item, index
                                        ) in VersionByProductAndProjectList"
                                        :key="index"
                                        :label="item.name"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="当前指派" prop="assignedto">
                                <el-select
                                    v-model="turnBugForm.assignedto"
                                    class="userSelect"
                                    placeholder="请选择指派人"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(item, index) in zenTaoUserList"
                                        :key="index"
                                        :label="item.value"
                                        :value="item.key"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="截止日期"
                                prop="deadline"
                                class="deadTime"
                            >
                                <el-date-picker
                                    class="userSelect"
                                    :editable="false"
                                    v-model="turnBugForm.deadline"
                                    :picker-options="pickerOptions"
                                    type="date"
                                    placeholder=""
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="BUG类型" prop="type">
                                <el-select
                                    v-model="turnBugForm.type"
                                    class="displayThree"
                                    placeholder="请选择BUG类型"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(item, index) in BugTypeList"
                                        :key="index"
                                        :label="item.valueName"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="操作系统" prop="os">
                                <el-select
                                    v-model="turnBugForm.os"
                                    class="displayThree"
                                    placeholder="请选择操作系统"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(item, index) in BugOsList"
                                        :key="index"
                                        :label="item.valueName"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="发现阶段" prop="browser">
                                <el-select
                                    v-model="turnBugForm.browser"
                                    class="displayThree"
                                    placeholder="请选择发现阶段"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(
                                            item, index
                                        ) in BugDiscoveryStageList"
                                        :key="index"
                                        :label="item.valueName"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row> </el-row>
                    <el-row>
                        <el-col :span="14" style="height: 40px">
                            <el-form-item label="BUG标题" prop="title">
                                <el-input
                                    class="bugTitle"
                                    v-model="turnBugForm.title"
                                    placeholder="请输入BUG标题"
                                ></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="5">
                            <el-form-item label="严重程度" prop="severity">
                                <el-select
                                    v-model="turnBugForm.severity"
                                    class="pointParst"
                                    placeholder="严重程度"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="(item, index) in BugSeverityList"
                                        :key="index"
                                        :label="item.valueName"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="优先级" prop="pri">
                                <el-select
                                    v-model="turnBugForm.pri"
                                    class="pointParst"
                                    filterable
                                    clearable
                                    placeholder="优先级"
                                >
                                    <el-option
                                        v-for="(item, index) in PriList"
                                        :key="index"
                                        :label="item.valueName"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24" style="margin-bottom: 6px">
                            <el-form-item
                                label="重现步骤"
                                class="questionDesc"
                                prop="steps"
                            >
                                <el-upload
                                    class="avatar-uploader quill-img"
                                    :action="fileUpload"
                                    :on-change="imgSaveToUrl"
                                    :headers="importHeaders"
                                    :show-file-list="false"
                                    :on-success="quillImgSuccess"
                                    :on-error="uploadError"
                                    :before-upload="quillImgBefore"
                                    accept=".jpg,.jpeg,.png,.gif"
                                ></el-upload>

                                <!-- <vue-tinymce v-model="turnBugForm.steps" :setting="setting" /> -->
                                    <quill-editor v-model="turnBugForm.steps" ref="quillEditor" :options="editorOption">
                                    </quill-editor>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="抄送给" prop="mailto">
                                <el-select
                                    v-model="turnBugForm.mailto"
                                    class="userSelect"
                                    placeholder="请选择抄送给"
                                    filterable
                                    clearable
                                    multiple
                                >
                                    <el-option
                                        v-for="(item, index) in zenTaoUserList"
                                        :key="index"
                                        :label="item.value"
                                        :value="item.key"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="计划解决版本/日期"
                                prop="keywords"
                                class="solutionVersion"
                            >
                                <el-input
                                    class="userSelect"
                                    v-model="turnBugForm.keywords"
                                    placeholder="例：V2.2.100.0/2019年4月9日"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col style="height: 65px">
                            <el-form-item label="添加附件" class="uploadFiles">
                                <br />
                                <el-upload
                                    class="upload-demo"
                                    :action="fileUpload"
                                    :on-success="onFileSuccess"
                                    :on-remove="onFileRemove"
                                    :headers="importHeaders"
                                    :on-error="onFileError"
                                    :file-list="bugFileUploadList"
                                    multiple
                                    :limit="3"
                                >
                                    <el-button
                                        size="small"
                                        type="primary"
                                        class="loadFile"
                                        >点击上传</el-button
                                    >
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <!-- 大图展示区域 -->
        <CommonDialog
            title="图片"
            width="75%"
            v-bind:dialogVisible="detailedContentDialogVisible"
            @on-change-dialogVisible="detailedContentChange"
            class="lookInfo"
            top="5vh"
        >
            <template #body>
                <div class="detailedContentDisplay" v-html="detailedContent">
                    {{ detailedContent }}
                </div>
            </template>
        </CommonDialog>
    </div>
</template>
<script>
import { FeedBack } from '@/api/feedBack/server'
import CommonDialog from '@/components/commonDialog/commonDialog.vue'
import { quillEditor, Quill } from 'vue-quill-editor'
import { ImageExtend, QuillWatch } from 'quill-image-extend-module'
import axios from 'axios'
Quill.register('modules/ImageExtend', ImageExtend)
// import axios from "axios"
// 工具栏配置
const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
    ['blockquote', 'code-block'], // 引用  代码块
    [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
    [{ indent: '-1' }, { indent: '+1' }], // 缩进
    [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
    [{ 'script': 'sub' }, { 'script': 'super' }],
    [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
    [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
    [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
    [{ 'font': [] }],
    [{ align: [] }], // 对齐方式
    ['clean'], // 清除文本格式
    ['link', 'image'] // 链接、图片、视频
]

export default {
    name: 'turnBug',
    components: {
        CommonDialog,
        quillEditor
    },
    props: {},
    beforeDestroy() {
        this.bugFileUploadList = []
    },

    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    const _now = Date.now()
                    const seven = 1 * 24 * 60 * 60 * 1000
                    const sevenDays = _now - seven
                    return time.getTime() < sevenDays
                }
            },
            // 本地路径
            localFile: {},
            detailedContent: '',
            detailedContentDialogVisible: false, // 大图展示区域
            // 本地图片
            loadImageNow: '',
            feedProblemDescribe: '',
            encLosureList: [],

            /* 得到token */
            importHeaders: { token: JSON.parse(sessionStorage.getItem('USERINFO')).token },

            /* 产品名称 */
            productID: '',
            /* 登录用户信息 */
            userInfo: {},
            /* 转BUG表单 */
            turnBugForm: {
                product: '',
                attachFileIds: [], // 附件Id资源列表
                editorFileIds: [],
                openedby: '', // 创建人
                branch: 0,
                module: '', // 模块
                project: '', // 项目
                openedbuild: '', // 影响版本
                assignedto: '', // 指派人
                deadline: '', // 截止日期
                type: '', // BUG类型
                title: '', // BUG标题
                browser: '', // 发现阶段
                severity: '', // 严重程度
                pri: '', // 优先级
                steps:
                    '', // 重现步骤
                mailto: '', // 抄送给
                keywords: '', // 计划解决版本日期/时间
                os: '', // BUG来源
                feedbackUrl: `${process.env.VUE_APP_BASE_API}`, // 上传路径
                feedbackId: '',
                problemDescribe: ''
            },
            /* 禅道 */

            /* 禅道 产品的type类型 */
            productType: '',
            // 禅道定制化
            customFlagList: [],
            // 禅道用户列表
            zenTaoUserList: [],
            // 产品详情
            // productInfo: {},
            // 禅道计划
            ListProductPlan: [],
            // 禅道模块
            ModuleList: [],
            // 优先级
            PriList: [],
            // 禅道来源
            SourceList: [],
            // 紧急程度
            UrgentList: [],
            // 禅道 产品关联项目
            ProjectList: [],
            // 禅道 发现阶段
            BugDiscoveryStageList: [],
            // 禅道  BUG类型
            BugTypeList: [],
            // 禅道  严重程度
            BugSeverityList: [],
            // 禅道  影响版本
            VersionByProductAndProjectList: [],
            // 禅道  BUG来源
            BugOsList: [],
            // 禅道  产品分支
            ProductBranchList: [],
            // 禅道 文件上传
            fileUpload: `${process.env.VUE_APP_GOLDWIND_BASE_API}/v2/zentao/file/upload`,
            // 附件上传文件列表
            bugFileUploadList: [],
            allProductList: [],

            // 表单验证规则
            turnBugFormRules: {
                product: [
                    {
                        required: true,
                        message: '',
                        trigger: 'change'
                    }
                ],

                module: [{ required: true, message: '', trigger: 'change' }],
                project: [{ required: true, message: '', trigger: 'change' }],
                openedbuild: [{ required: true, message: '', trigger: 'change' }],
                deadline: [{ required: true, message: '', trigger: 'change' }],
                type: [{ required: true, message: '', trigger: 'change' }],
                browser: [{ required: true, message: '', trigger: 'change' }],
                severity: [{ required: true, message: '', trigger: 'change' }],
                pri: [{ required: true, message: '', trigger: 'change' }],
                branch: [{ required: true, message: '', trigger: 'change' }],
                os: [{ required: true, message: '', trigger: 'change' }],
                title: [{ required: true, message: '', trigger: 'change' }],
                keywords: [{ required: false, message: '', trigger: 'change' }]
            },

            // 富文本编辑器
            editorOption: {
                modules: {
                    clipboard: {
                        // 粘贴版，处理粘贴时候带图片
                        matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]]
                    },
                    ImageExtend: { // 如果不作设置，即{}  则依然开启复制粘贴功能且以base64插入
                        name: 'file', // 图片参数名
                        // size: 3, // 可选参数 图片大小，单位为M，1M = 1024kb
                        action: `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/zentao/file/upload', // 服务器地址, 如果action为空，则采用base64插入图片
                        // response 为一个函数用来获取服务器返回的具体图片地址
                        // 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
                        // 则 return res.data.url
                        response: (res) => {
                            return res.data.imgUrl
                        },
                        headers: (xhr) => {
                            xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token)
                        } // 可选参数 设置请求头部
                    },
                    toolbar: {
                        container: toolbarOptions,
                        handlers: {
                            'image': function() { // 劫持原来的图片点击按钮事件
                                QuillWatch.emit(this.quill.id)
                            }
                        }
                    }
                }
            },

            setting: {
                branding: false,
                menubar: false,
                toolbar:
                    'undo redo | formatselect alignleft aligncenter alignright alignjustify  numlist bullist  | fontselect fontsizeselect forecolor backcolor | image code | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat | ',
                toolbar_drawer: 'sliding',
                quickbars_selection_toolbar:
                    'removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor',
                plugins: 'link image  table lists fullscreen',
                language: 'zh_CN',
                init_instance_callback: (editor) => {
                    if (this.content) {
                        editor.setContent(this.content)
                    }
                    this.finishInit = true
                    editor.on('NodeChange Change SetContent KeyUp', () => {
                        this.hasChanged = true
                    })
                }, // 上传图片
                convert_urls: false,
                content_style: 'img {width:80px !important }', // 初始化赋值
                powerpaste_word_import: 'merge', // 复制粘贴的文字样式处理 参数可以是propmt, merge, clean，效果自行切换对比
                powerpaste_html_import: 'merge', // 复制粘贴的html样式处理 propmt, merge, clean
                powerpaste_allow_local_images: true, // 复制粘贴图书是否允许本地图片
                paste_data_images: false,
                automatic_uploads: true, // 开启点击图片上传时，自动进行远程上传操作
                paste_preprocess: (pluginApi, data) => {
                    // console.log(data);
                    // Apply custom filtering by mutating data.content
                    // For example:
                    const content = data.content

                    const newContent = this.yourCustomFilter(content)
                    data.content = newContent
                },
                images_upload_base_path: `${process.env.VUE_APP_GOLDWIND_BASE_API}`, // 图片上传的基本路径
                images_upload_url: '/v2/file/upload',
                images_upload_handler: (blobInfo, success, failure) => {
                    var xhr, formData

                    xhr = new XMLHttpRequest()
                    xhr.withCredentials = false
                    xhr.open(
                        'POST',
                        `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/file/upload'
                    )
                    xhr.setRequestHeader(
                        'token',
                        JSON.parse(sessionStorage.getItem('USERINFO')).token
                    )
                    // xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token);
                    formData = new FormData()
                    formData.append('file', blobInfo.blob())

                    formData.append('checkOfficeFmt', false)
                    formData.append('isTmp', false)
                    xhr.onload = function() {
                        var json

                        if (xhr.errcode === '0') {
                            failure('服务器错误:' + xhr.msg)
                            return
                        }
                        json = JSON.parse(this.responseText)
                        if (!json.data || typeof json.data.fileSourceId != 'string') {
                            failure('服务器错误')
                            return
                        }
                        success(
                            `${process.env.VUE_APP_GOLDWIND_BASE_API}` +
                            '/v2/file/download?' +
                            '&fileSourceId=' +
                            json.data.fileSourceId
                        )
                    }
                    xhr.send(formData)
                },
                image_advtab: false,
                language_url: 'tinymce/langs/zh_CN.js', // 语言包的路径
                elementpath: false, // 隐藏元素路径，不明白的可以切换true/false观察页面
                statusbar: false,
                resize: false,
                height: 400
            }
        }
    },
    computed: {
        visitedViews() {
            return this.$store.state.tagsView.visitedViews
        }
    },
    watch: {},
    created() { },
    activated() {
        this.GetListAllUser()
        this.turnBugForm.feedbackId = this.$route.query.id
        this.GetAllProductAsync().then(() => {
            this.getCategory(this.$route.query.id)
        })
        this.GetBugTypeList()
        this.GetBugDiscoveryStageList()
        this.GetBugSeverityList()
        this.GetPriList()
        this.GetBugOsList()
        this.getuserId()
    },
    mounted() {
        this.GetListAllUser()
        this.turnBugForm.feedbackId = this.$route.query.id
        this.GetAllProductAsync().then(() => {
            this.getCategory(this.$route.query.id)
        })
        this.GetBugTypeList()
        this.GetBugDiscoveryStageList()
        this.GetBugSeverityList()
        this.GetPriList()
        this.GetBugOsList()
        this.getuserId()

        // })
    },
    methods: {
        handleCustomMatcher(node, Delta) {
            console.log(Delta)
            const ops = []
            Delta.ops.forEach(op => {
                if (op.insert && typeof op.insert === 'string') { // 如果粘贴了图片，这里会是一个对象，所以可以这样处理
                    ops.push({
                        insert: op.insert
                    })
                } else {
                    console.log(op.insert)
                    console.log(op.insert.image)
                    const img = op.insert.image
                    this.downloadFileByBase64(img, 'quillEditor')
                }
            })
            Delta.ops = ops
            return Delta
        },
        dataURLtoBlob(dataurl, filename) {
            var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
            var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], filename, { type: mime })
        },

        // base64 文件流转图片下载
        downloadFileByBase64(img, refName) {
            console.log('img', img)
            if (img.indexOf('data:') !== -1) {
                console.log(this.dataURLtoBlob(img, 'image.png'))
                var formData
                formData = new FormData()
                formData.append('file', this.dataURLtoBlob(img, '123.png'))
                const imh = this.dataURLtoBlob(img, '123.png')
                console.log(imh)
                formData.append('checkOfficeFmt', false)
                formData.append('isTmp', false)
                axios({
                    method: 'post',
                    url: `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/zentao/file/upload',
                    data: formData,
                    headers: {
                        token: JSON.parse(sessionStorage.getItem('USERINFO')).token
                    }
                }).then(res => {
                    console.log('res----', res)
                    const quill = this.$refs[refName].quill
                    const length = quill.getSelection(true)
                    // 插入图片 res.info为服务器返回的图片地址
                    quill.insertEmbed(length.index, 'image', res.data.data.imgUrl)
                    // 调整光标到最后
                    quill.setSelection(length.index + 1)
                }).catch(err => {
                    console.log(err)
                })
            } else {
                const quill = this.$refs[refName].quill
                const length = quill.getSelection(true)
                // 插入图片 res.info为服务器返回的图片地址
                quill.insertEmbed(length.index, 'image', img)
                // 调整光标到最后
                quill.setSelection(length.index + 1)
            }
        },
        detailedContentChange() {
            this.detailedContentDialogVisible = false
            this.detailedContent = ''
        },
        /**
     * @description: 获取所有列表
     * @param {String} _id 路由携带ID
     */
        async getCategory(_id) {
            try {
                const result = await FeedBack.GetLoadAsync({ id: _id })
                if (result.success) {
                    this.turnBugForm.title = result.data.title
                    let arr = []
                    if (result.data.fileUrl != '' && result.data.fileUrl != null) {
                        const str = '[' + result.data.fileUrl + ']'
                        arr = JSON.parse(str)
                        // this.encLosureList = JSON.parse(str)
                    }
                    let string = ''
                    for (const item of arr) {
                        string += `<p><a href="${process.env.VUE_APP_GOLDWIND_BASE_API}/v2/file/download?fileSourceId=${item.url}" rel="noopener noreferrer" target="_blank">${item.name}</a></p>`
                    }
                    console.log(string)
                    const str = result.data.problemDescribe
                    const quill = this.$refs.quillEditor.quill
                    const aaaaaa = `<p>[程序版本]<span style="color:red;">(必填)</span>：</p><p>[问题描述]<span style="color:red;">(必填)</span>：${str}</p><p>[故障日志]<span style="color:red;">(必填)</span>：</p><p>[初步分析报告]<span style="color:red;">(必填)</span>：</p><p>[附件需上传]<span style="color:red;">(必填)</span>：</p><p>[反馈相关附件]：${string}</p>`
                    quill.root.innerHTML = aaaaaa
                } else {
                    this.$message.error(result.message)
                }
            } catch (err) {
                console.log(err)
                this.$message.error('服务544444器异常', err)
            }
        },
        /**
     * @description: 返回至上一个页面
     */
        toBefore() {
            const selectedTag = this.currentViews(this.$route)
            this.$store.dispatch('tagsView/delView', selectedTag)
            this.$router.go(-1)
        },
        currentViews(tag) {
            let objs = {}
            for (let i = 0; i < this.visitedViews.length; i++) {
                if (this.visitedViews[i].path == tag.path) {
                    objs = this.visitedViews[i]
                }
            }

            return objs
        },

        /**
     * @description: 获取所有产品信息
     */
        async GetAllProductAsync() {
            try {
                const result = await FeedBack.GetAllProductAsync()
                if (result.success) {
                    this.allProductList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 监听 产品的改变
     * @param {String} _val 产品ID
     */
        productChange(_val) {
            this.turnBugForm.product = _val
            this.turnBugForm.module = ''
            this.turnBugForm.openedbuild = ''
            this.turnBugForm.project = ''
            this.turnBugForm.branch = 0
            this.ProductBranchList = []
            this.ProjectList = []
            this.VersionByProductAndProjectList = []
            /* 反查产品类型 */
            this.allProductList.forEach(item => {
                if (item.productId == _val) {
                    this.productType = item.type
                }
            })
            /* 重新请求值 */
            this.GetProjectList(_val)
            this.GetModuleList(_val)
            if (this.productType !== 'normal') {
                // 获取产品分支
                this.GetProductBranchList(_val)
            }
        },

        /**
     * @description: 获取当前用户信息
     */
        async getuserId() {
            try {
                const result = await FeedBack.UserGetUserInfoAsync()
                if (result.success) {
                    this.userInfo = result.data
                    this.turnBugForm.openedby = result.data.id
                }
            } catch (err) {
                console.log(err)
            }
        },

        //     /**
        //  * @description: 获取产品详情
        //  */
        async GetProductInfo(val) {
            try {
                const result = await FeedBack.GetProductInfo({
                    productId: val
                })
                if (result.success) {
                    this.productType = result.data.type
                    /*
                判断产品信息的type类型，判断是否有分支
                branch
                normal  ------------ 没有分支
                platform
              */
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 获取禅道模块
     */
        async GetModuleList(_val) {
            try {
                const result = await FeedBack.GetModuleList({
                    productId: _val
                })
                if (result.success) {
                    this.ModuleList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 产品关联项目
     * @param {String} id 产品ID
     */
        async GetProjectList(id) {
            try {
                const result = await FeedBack.GetProjectList({ id: id })
                if (result.success) {
                    this.ProjectList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 发现阶段下拉
     */
        async GetBugDiscoveryStageList() {
            try {
                const result = await FeedBack.GetBugDiscoveryStageList()
                if (result.success) {
                    this.BugDiscoveryStageList = result.data
                    this.turnBugForm.browser = 'outside'
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 禅道 BUG类型
     */
        async GetBugTypeList() {
            try {
                const result = await FeedBack.GetBugTypeList()
                if (result.success) {
                    this.BugTypeList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 禅道 严重程度
     */
        async GetBugSeverityList() {
            try {
                const result = await FeedBack.GetBugSeverityList()
                if (result.success) {
                    this.BugSeverityList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
         * @description: 禅道 优先级
         *
        /* 禅道 优先级 */
        async GetPriList() {
            try {
                const result = await FeedBack.GetPriList()
                if (result.success) {
                    this.PriList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 监听 项目改变更新影响版本下拉
     *@param {String} _val 项目ID
     */
        projectChange(_val) {
            // console.log(_val)
            this.VersionByProductAndProjectList = []
            // 获取版本
            this.GetVersionByProductAndProjectList(_val)
        },

        /**
     * @description: 禅道 影响版本
     * @param {String} _val
     */
        async GetVersionByProductAndProjectList(_val) {
            try {
                const result = await FeedBack.GetVersionByProductAndProjectList({
                    productId: this.turnBugForm.product,
                    projectId: _val
                })
                if (result.success) {
                    this.VersionByProductAndProjectList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 禅道 BUG来源
     */
        async GetBugOsList() {
            try {
                const result = await FeedBack.GetBugOsList()
                if (result.success) {
                    this.BugOsList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },
        /**
     * @description: 禅道用户列表
     */
        async GetListAllUser() {
            try {
                const result = await FeedBack.GetListAllUser()
                if (result.success) {
                    this.zenTaoUserList = result.data
                    // console.log(result.data)
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 禅道 产品分支
     * @param {String} _id 产品ID
     * @return {*}
     */
        async GetProductBranchList(_id) {
            try {
                const result = await FeedBack.GetProductBranchList({ productId: _id })
                if (result.success) {
                    // let branchArray=
                    this.ProductBranchList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },
        /**
     * @description: 禅道 确认转BUG
     */
        SaveBug() {
            console.log(this.turnBugForm.steps)
            const content = this.turnBugForm.steps
            if (content.indexOf('<img') != -1) {
                const imgReg = /<img.*?(?:>|\/>)/gi
                const imgArray = content.match(imgReg)
                console.log(imgArray)
                let detailedContent = null
                for (const i in imgArray) {
                    if (Object.hasOwnProperty.call(imgArray, i)) {
                        const element = imgArray[i]
                        detailedContent += element
                    }
                }
                console.log(detailedContent)
            }
            this.$refs['dynamicValidateForm'].validate(valid => {
                if (valid) {
                    this.turnBug()
                } else {
                    this.$message.error('请把必填项填写完整')
                    console.log('error submit!!')
                    return false
                }
            })
        },

        /**
     * @description: 转BUG方法
     */
        async turnBug() {
            const loading = this.$loading({
                lock: true,
                text: '数据加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            this.turnBugForm.feedbackUrl += `Details?feedBackId=${this.$route.query.id}`
            const amrStr = this.turnBugForm.mailto.toString()
            this.turnBugForm.mailto = amrStr
            for (const item of this.bugFileUploadList) {
                this.turnBugForm.attachFileIds.push(item.id)
            }
            try {
                const result = await FeedBack.ChangeBug(this.turnBugForm)
                if (result.success) {
                    // 转bug成功之后,清除文件内容,避免出错
                    loading.close()
                    this.bugFileUploadList = []
                    const selectedTag = this.currentViews(this.$route)
                    this.$store.dispatch('tagsView/delView', selectedTag)
                    this.$router.go(-1)
                    // localStorage.setItem('fir', '转BUG')
                } else {
                    this.bugFileUploadList = []
                    this.$message.error(result.message)
                    loading.close()
                }
            } catch (err) {
                this.bugFileUploadList = []
                console.log(err)
            }
        },

        /**
     * @description: 附件上传成功钩子函数
     * @param {Object} _response 文件上传成功返回的参数
     * @param {Object} _file 上传成功的文件
     * @param {Array} _fileList 加载器内存储的文件列表
     */
        onFileSuccess(_response, _file, _fileList) {
            console.log(_response, _file, _fileList)
            if (_response.errcode == '0') {
                this.bugFileUploadList.push({
                    url: _response.data.imgUrl,
                    name: _response.data.title + '.' + _response.data.extension,
                    id: _response.data.id
                })
                // TODO: 文件上传成功提示
                this.$message.success('文件上传成功')
            } else {
                this.$message.error(_response.msg || '上传失败')
            }
        },
        onFileRemove(_file, _fileList) {
            console.log(_file, _fileList)
            for (let index = 0; index < this.bugFileUploadList.length; index++) {
                if (_file.id === this.bugFileUploadList[index].id) {
                    this.bugFileUploadList.splice(index, 1)
                }
            }
            console.log(this.bugFileUploadList)
            // this.demandFileUploadList = _fileList
        },

        /**
     * @description: 附件上传失败的钩子函数
     */
        onFileError() {
            this.$message.error('上传失败')
        },

        /**
     * @description: 重现描述文本框 文件上传之前的钩子函数
     * @param {file} file
     */
        quillImgBefore(param) {
            if (!param) {
                this.$message.error('请选择图片')
                return
            }
            const { type: originType } = param
            const typeArray = ['JPG', 'JPEG', 'PNG', 'GIF']
            var type = originType.split('/')[1].toUpperCase()
            if (typeArray.indexOf(type) == -1) {
                this.$message.error('不支持的文件类型')
                return false
            }
            // const IMG_SIZE = 1024 * 200 // 2M
            // if (originSize > IMG_SIZE) {
            //     this.$message.error('上传失败：单个文件不能超过200KB')
            //     return false
            // }
        },
        /**
     * @description: 重现描述文本框 文件上传成功的钩子函数
     * @param {Object} res 文件上传成功返回的参数
     * @return {*}
     */
        quillImgSuccess(res) {
            // 如果上传成功
            // 获取富文本组件实例
            const quill = this.$refs.quillEditor.quill
            if (res.errcode == '0') {
                console.log(res.data)
                // TODO: 文件上传成功提示
                this.$message.success('文件上传成功')
                const range = quill.getSelection()
                quill.insertEmbed(range.index, 'image', res.data.imgUrl)
                // 调整光标到最后
                quill.setSelection(length + 1)
                this.turnBugForm.editorFileIds.push(res.data.id)
            } else {
                this.$message.error(res.msg || '上传失败')
            }
        },

        /**
     * @description: 重现描述文本框 文件上传图片失败的钩子函数
     */
        // 富文本图片上传失败
        uploadError() {
            // loading动画消失
            this.$message.error('图片插入失败')
        },

        /**
     * @description: 重现富文本框 文件状态改变的钩子函数
     * @param {file} file
     */
        imgSaveToUrl(file) {
            // 也可以用file
            this.localFile = file.raw // 或者

            // 转换操作可以不放到这个函数里面，
            // 因为这个函数会被多次触发，上传时触发，上传成功也触发
            const reader = new FileReader()
            reader.readAsDataURL(this.localFile) // 这里也可以直接写参数event.raw

            // 转换成功后的操作，reader.result即为转换后的DataURL ，
            // 它不需要自己定义，你可以console.log(reader.result)看一下
            reader.onload = () => {
                // console.log(reader.result)
                this.loadImageNow = reader.result
            }
        }
    }
}
</script>
<style scoped lang="less" src="./turnBug.less"></style>
<style scoped>
::v-deep .ql-editor li {
    list-style-type: decimal !important;
    list-style-position: inside !important;
}
::v-deep .ql-editor ul > li:before {
    content: "\2022";
}

::v-deep .ql-editor ul > li::marker {
    content: "";
    display: none;
}

::v-deep .ql-editor li:before {
    display: inline-block;
    white-space: nowrap;
    width: 1.2em;
}
.sticky-headers {
    position: sticky;
    top: 0;
    min-height: 50px;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    z-index: 1;
    padding: 0 30px;
}
</style>
